//引入接口
import { login, logout, getInfo } from '@/api/user'
//获取token、设置token、移出token
import { getToken, setToken, removeToken } from '@/utils/auth'
//引入路由器 resetRouter重置路由器
//为什么要重置？
//如果一个用户退出登录另一个新的用户需要登录，路由系统恢复原始状态
import router, { resetRouter } from '@/router'

//状态
const state = {
  token: getToken(), //token 从cookie中获取token
  id: null,
  avatar: "",
  roleList: [],
  permissionList: [],
}

//改变状态的唯一途径
const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_ID: (state, id) => {
    state.id = id
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLELIST: (state, roleList) => { 
    state.roleList = roleList
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissionList = permissions
  }
}

const actions = {
  // 用户登录
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
          const { data } = response
          commit('SET_TOKEN', data.token)
          setToken(data.token)
          resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          reject('获取用户信息失败请重新登录.')
        }

        // 从data中解构出具体信息：角色、用户名、头像、介绍
        const { roleList, id, avatar, permissionList } = data

        // 结构用户角色信息，[]必须不为空
        if (!roleList || roleList.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }
        //赋值操作
        commit('SET_ROLELIST', roleList)
        commit('SET_ID', id)
        commit('SET_AVATAR', avatar)
        commit('SET_PERMISSIONS', permissionList)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 用户退出登录
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_ID', null)
        commit('SET_AVATAR', '')
        commit('SET_TOKEN', '')
        commit('SET_ROLELIST', [])
        commit('SET_PERMISSIONS', [])
        removeToken()
        resetRouter()
        dispatch('tagsView/delAllViews', null, { root: true })
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLELIST', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
